var windowHeight = 0;
var intervalId = 0;
$(document).ready(function () {
    $("#inquiry").css("display", "block");
    $("a.tab-txt").click(function () {
        $("a.tab-txt").removeClass("tab-index");
        var ss = $(this);
        ss.addClass("tab-index");
        // window.location.href='tab_test.html';

        $("div.full-page").css("display", "none");
        let select = ss.attr("sid");
        $(select).css("display", "block");
    });

    windowHeight = window.innerHeight;
    console.log("windowHeight: ", windowHeight);

    // let user = getUserInfo();
    // console.log("UserInfo: ", user);
    // $("#office").text("科室：" + user.deptName);
    // $("#role").text("角色：" + user.labelName);
    // $("#name").text(user.nickname);
    // $("#head").attr("src", user.icon);

    $("#office").text("科室：" + $.cookie("deptName"));
    switch ($.cookie("type")) {
        case "1":
            $("#role").text("角色：护士");
            break;
        case "2":
            $.cookie("doctorLabel") === "1" ? $("#role").text("角色：医生") : $("#role").text("角色：专家");
            break;
        case "3":
            $("#role").text("角色：药师");
            break;
        case "4":
            $("#role").text("角色：医院");
            break;
    }
    $("#name").text($.cookie("truename"));

    //获取医生常用资料，设置cookie
    $.ajax({
        url: $.cookie("tempUrl") + "hSysDoctor/selectByPrimaryKey?id=" + $.cookie("doctorId"),
        type: "GET",
        success: function (result) {
            if (result.code === 200) {
                $.cookie('icon', result.data.icon, {path: '/'});
                $("#head").attr("src", $.cookie("icon"));
            }
        }
    });

    //图文还是视频
    if (sessionStorage.getItem("changeLeft")) {
        $("#inquiryIframe").attr("src", "pic_txt_full.html")
    } else {
        sessionStorage.removeItem("changeLeft")
        $("#inquiryIframe").attr("src", "inquiry.html")
    }

    getListData()
    // intervalId = window.setInterval(function() {
    // 	getListData()
    // }, 10000);
});

// function findReceivingTreatmentRing() {
//     $(document).ready(function () {
//         $.ajax({
//             url: $.cookie("tempUrl") + "omsring/findReceivingTreatmentRing?doctorId=" + $.cookie("doctorId"),
//             type: "POST",
//             success: function (result) {
//                 if (result.code === 200) {
//                     console.log("findReceivingTreatmentRing")
//                     if (result.data != null && result.data !== "null" && result.data.roomid != null && result.data.roomid !== "0") {
//                         let roomId = result.data.roomid;
//
//
//                     }
//                 } else {
//                     layer.msg('请求异常', {icon: 7, anim: 6});
//                 }
//             },
//             error: function (e) {
//                 console.error("加载患者呼叫失败！");
//             }
//         });
//     });
// }
var lockPage;

function findGrabSheetList() {
    if ($.cookie("unlock") == 0) {
        if (lockPage == undefined) {
            $.ajax({
                type: "PUT",
                url: serverApi + "/sysdoctor/logout?doctorId=" + $.cookie("doctorId"),
                success: function (result) {
                    if (result.code === 200) {
                        onLockClick()
                    }
                }
            });
        }
    } else if ($.cookie("password") === undefined || $.cookie("password") === '') {
        layer.alert('检测到长期未登录，请重新登陆', function (index) {
            window.location.href = "login.html";
            layer.close(index);
        });
    } else {
        //保持登陆状态
        $.ajax({
            url: $.cookie("tempUrl") + "sysdoctor/doctorsLogin",
            type: "POST",
            datatype: "application/json",
            contentType: "application/json;charset=utf-8",
            headers: {
                "Content-Type": 'application/x-www-form-urlencoded'
            },
            data: {
                phone: $.cookie("phone"),
                password: strEnc($.cookie("password"), desKey1, desKey2, desKey3),
                // password: $("#password").val(),
                type: $.cookie("type")
            },
            success: function (result) {
                if (result.code === 200) {
                    console.log("保持登陆状态")
                }
            },
        });

        //检查是否有新消息
        $.ajax({
            url: $.cookie("tempUrl") + "sysdoctornews/findDnewVO?doctorId=" + $.cookie("doctorId"),
            type: "POST",
            success: function (result) {
                if (result.code === 200) {
                    if (result.data.isnot === 1) {
                        $(".findDnewVO").css("display", "")
                    } else {
                        $(".findDnewVO").css("display", "none")
                    }
                }
            }
        });
        //检查是否有新订单
        console.log("findGrabSheetList() execute. TcpLink:" + sessionStorage.getItem('tcpLink'))
        if (sessionStorage.getItem('tcpLink') !== "linking") {
            //清空缓存，重置首页内容
            sessionStorage.removeItem('obj');
            $(".tempShowRelationship").css("display", "")
            $("#clientInfoOver").css("display", "")
            //加载抢单列表
            $(document).ready(function () {
                // //查询是否有新消息（new）
                // $.ajax({
                //     url: $.cookie("tempUrl") + "sysdoctor/get01De?doctorId=" + $.cookie("doctorId"),
                //     type: "POST",
                //     success: function (result) {
                //         if (result.code === 200) {
                //             console.log(result.data)
                //             //视频
                //             if (result.data.num4 === 1) {
                //                 //监听循环播放
                //                 // $(ringLai).bind("ended", function () {
                //                 //     ringLai.play();
                //                 // });
                //                 ringLai.play(); //播放 mp3这个音频对象
                //                 $.cookie("doctorLabel") === "1" ? $.cookie('tempUrlTemp', 'findGrabSheetList?deptId=' + $.cookie("deptId"), {path: '/'}) : $.cookie('tempUrlTemp', 'findReceivingTreatmentRingPC?doctorId=' + $.cookie("doctorId"), {path: '/'});
                //                 showInquiryList();
                //             }
                //             //图文
                //             if (result.data.num5 === 1) {
                //                 ringLai.play(); //播放 mp3这个音频对象
                //                 $.cookie('tempUrlTemp', 'finOmsImageTextAppVOList?doctorId=' + $.cookie("doctorId"), {path: '/'});
                //                 showInquiryList();
                //             }
                //         }
                //     }
                // });
                //查询是否有新视频问诊（old）
                $.ajax({
                    url: $.cookie("tempUrl") + "omsring/findGrabSheetList?deptId=" + $.cookie("deptId") + "&doctorId=" + $.cookie("doctorId"),
                    type: "POST",
                    success: function (result) {
                        if (result.code === 200 && result.data.length > 0) {
                            // //监听循环播放
                            // $(ringLai).bind("ended", function () {
                            //     ringLai.play();
                            // });
                            ringLai.play(); //播放 mp3这个音频对象
                            $.cookie("doctorLabel") === "1" ? $.cookie('tempUrlTemp', 'findGrabSheetList?deptId=' + $.cookie("deptId") + "&doctorId=" + $.cookie("doctorId"), {path: '/'}) : $.cookie('tempUrlTemp', 'findReceivingTreatmentRingPC?doctorId=' + $.cookie("doctorId"), {path: '/'});
                            showInquiryList();
                        } else {
                            //查询是否有新图文问诊
                            $.ajax({
                                url: $.cookie("tempUrl") + "omsring/finOmsImageTextAppVOList?doctorId=" + $.cookie("doctorId"),
                                type: "POST",
                                success: function (result) {
                                    if (result.code === 200 && result.data.length > 0) {
                                        $(result.data).each(function (index, element) {
                                            if (element.doctorAid == null || element.doctorAid === "0") {
                                                ringLai.play(); //播放 mp3这个音频对象
                                                $.cookie('tempUrlTemp', 'finOmsImageTextAppVOList?doctorId=' + $.cookie("doctorId"), {path: '/'});
                                                showInquiryList();
                                            }
                                        })
                                    }
                                }
                            });
                        }
                    }
                });
            });
        } else {
            $(".tempShowRelationship").css("display", "none")
            $("#clientInfoOver").css("display", "none")
            let memberData = JSON.parse(sessionStorage.getItem('memberData'));
            $("#clientName").text(memberData.name)
            $("#clientGender").text(memberData.gender === 1 ? "男" : "女")
            $("#clientAge").text(memberData.age + "岁")
            $("#source").val(memberData.sourceType)
        }
    }
}


// setInterval('findReceivingTreatmentRing()', 5000);//轮询执行，5000ms一次
setInterval('findGrabSheetList()', 5000);//轮询执行，5000ms一次

//绑定关系
function bendRelationship() {
    layer.msg("此功能还处于内测状态，暂未开放")
}

//添加标签
function addLabel() {
    layer.open({
        title: "添加标签",
        type: 2,
        area: ["340px", "240px"],
        content: "labelAdd.html",
        shadeClose: true,
        success: function () {

        }
    });
}

function showDialog() {
    $.addTag.Confirm("添加标签", "添加", function (tag) {
        console.log("home tag: ", tag);
    });
}

var isHealth = false;

function showNotify() {
    if (isHealth == false) {
        $("#health").hide();
        $("#frame").show();
        isHealth = true;
        document.getElementById("myIframe").src = "message_center.html";
    }
}

var isVideo = true;

function switchPictxt() {
    inquiryIframe.window.switchChat();
    // if (isVideo) {
    // 	document.getElementById("inquiryIframe").src = "pic_txt.html";
    // 	isVideo = false;
    // } else {
    // 	document.getElementById("inquiryIframe").src = "inquiry.html";
    // 	isVideo = true;
    // }
}

function logout() {
    layer.confirm('是否退出登陆?', {icon: 3, title: '系统提示'}, function (index) {
        //do something
        $.ajax({
            type: "PUT",
            contentType: "application/x-www-form-urlencoded",
            url: serverApi + "/sysdoctor/logout?doctorId=" + $.cookie("doctorId"),
            success: function (result) {
                if (result.code === 200) {
                    window.location.href = "login.html";
                    layer.close(index);
                } else {
                    window.location.href = "login.html";
                    layer.close(index);
                }
            },
            error: function (e) {
                window.location.href = "login.html";
                layer.close(index);
            }
        });
    });
}


function onLockClick() {
    $.cookie('unlock', 0, {path: '/'});
    lockPage = layer.open({
        type: 2,
        title: false,
        area: ['450px', '396px'],
        closeBtn: 0,
        shadeClose: false,
        shade: 0.5,
        scrollbar: false,
        skin: 'lock-skin',
        content: 'lock.html',
        success: function (layero, index) {
            // var body = parent.parent.layer.getChildFrame('body', index);
            // //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
            // var iframeWin = parent.parent.window[layero.find('iframe')[0]['name']];
        }
    });
}

var isShowList = false;

function showInquiryList() {
    if (!isShowList) {
        $("#bcDiv").show();
        document.getElementById("bcDiv").style.height = (windowHeight - 130) + "px";
        document.getElementById("bcIframe").src = "inquiry_list.html";
        isShowList = true;
    }
    try {
        window.setTimeout(function () {
            // bcIframe.window.setInquiryData(inquiryListData);
        }, 300);
    } catch (e) {
        //TODO handle the exception
        console.log("setData e: ", e);
    }
}

function hideInquiryList() {
    if (isShowList) {
        $("#bcDiv").hide();
        isShowList = false;
    }
}

let inquiryListData = [];

function getListData() {
    // let user = getUserInfo();
    // if (isNullOrEmpty(user) || isNullOrEmpty(user.id)) {
    //     window.location.href = "login.html";
    //     return;
    // }
    inquiryListData = [];
    post("/a02/omsring/findGrabSheetList", {
            deptId: user.deptId,
            doctorId: user.id
        },
        function (res) {
            console.log("vidoe res: ", res);
            if (res.code === 200) {
                let list = res.data;
                var convertData = [];
                for (var i = 0; i < list.length; i++) {
                    let item = {};
                    item.name = list[i].name;
                    item.gender = getGender(list[i].gender);
                    item.location = getLocation(list[i].ly);
                    item.source = list[i].sourceId;
                    item.typeName = getType(1);
                    convertData.push(item);
                }
                inquiryListData.push.apply(inquiryListData, convertData);
                if (inquiryListData.length > 0) {
                    showInquiryList();
                }
            }
        },
        function (e) {
            console.log("e: ", e);
        });
    post("/a02/omsring/findOmsImageTextVOList", {
            doctorId: user.id,
            pageNum: 1
        },
        function (res) {
            console.log("img txt res: ", res);
            if (res.code === 200) {
                let list = res.data.dataList;
                var convertData = [];
                for (var i = 0; i < list.length; i++) {
                    let item = {};
                    item.name = list[i].memberName;
                    item.gender = getGender(list[i].gender);
                    item.location = getLocation(list[i].ly);
                    item.source = list[i].sourceId;
                    item.typeName = getType(2);
                    convertData.push(item);
                }
                inquiryListData.push.apply(inquiryListData, convertData);
                if (inquiryListData.length > 0) {
                    showInquiryList();
                }
            }
        },
        function (e) {
            console.log("e: ", e);
        });

    //下面为测试代码
    inquiryListData.push({
        // "age": 23,
        // "fwqmc": "服务别名",
        // "gender": 1,
        // "icon": "https://yjyl-1301813220.cos.ap-guangzhou.myqcloud.com/efd972e5fe0d4f6e82f123adb1d11fa8.jpg",
        // "id": "fsaffadsfasf",
        // "ip": "192.168.1.25",
        // "ly": 2,
        // "memberId": 0,
        // "menberAge": 0,
        // "menberIcon": "https://yjyl-1301813220.cos.ap-guangzhou.myqcloud.com/efd972e5fe0d4f6e82f123adb1d11fa8.jpg",
        // "menberName": "测试账号",
        // "menberPhone": "888888",
        // "menberSex": 2,
        // "name": "测试账号",
        // "panelType": 2,
        // "rctid": "afdsdasfdasfsad",
        // "sfzdys": 0,
        // "sourceId": "背景一段",
        // "timeaa": "2021-04-15 13:33:49",
        // "timec": "2021-04-15 13:33:49",
        // "yuming": "string"
        'name': '测试账号',
        'gender': '1',
        'location': '2',
        'source': '北京移动',
        'type': '1',
        'age': '26岁',
        'index': 0
    })

    inquiryListData.push({
        // "doctorAid": "12432",
        // "fwqmbm": "测试别名",
        // "name": "的方式",
        // "id": "6454",
        // "ip": "192.168.6.52",
        // "ly": 1,
        // "memberName": "string",
        // "memberNames": "string",
        // "prescription": 1,
        // "sfzdys": 1,
        // "sourceId": "67857",
        // "stat": 1,
        // "timeaa": "2021-04-15 13:54:27",
        // "xxnum": 4,
        // "yuming": "string"
        'name': '测试账号2',
        'gender': '2',
        'location': '1',
        'source': '医健云联VIP',
        'type': '2',
        'age': '25岁',
        'index': 1
    })
    showInquiryList();
}

function getGender(gender) {
    if (gender == 1) {
        return "男";
    } else if (gender == 2) {
        return "女";
    } else {
        return "未知";
    }
}

function getLocation(ly) {
    if (ly == 1) {
        return "本地";
    } else if (ly == 2) {
        return "外地";
    } else {
        return "未知";
    }
}

function getType(type) {
    if (type == 2) {
        return "图文问诊";
    } else {
        return "视频问诊";
    }
}

// function setClientInfo(info, type) {
//     console.log("info: ", info);
//     $("#clientInfoOver").hide();
//     $("#clientName").text(info.name);
//     $("#clientGender").text(getGender(info.gender));
//     $("#clientAge").text(info.age);
//     $("#source").val(info.source);
//     if (type == 3) {
//         inquiryIframe.window.switchChat(3);
//     } else if (type == 2) {
//         inquiryIframe.window.switchChat(2);
//     } else {
//         inquiryIframe.window.switchChat(1);
//     }
// }
